package com.lengxf.netty.config.handler;

import cn.hutool.json.JSONUtil;
import com.lengxf.netty.config.message.NettyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TriggerHandler extends ChannelInboundHandlerAdapter {
    private static final int TRY_TIMES = 3;
    private int currentTime = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        log.info("trigger heartbeat mechanism ...");
        if (evt instanceof IdleStateEvent event) {
            //相对于服务端 客户端是写事件 来触发心跳...
            if (event.state() == IdleState.WRITER_IDLE) {
                if (currentTime <= TRY_TIMES) {
                    currentTime++;
                    NettyMessage nettyMessage = new NettyMessage();
                    nettyMessage.setText("发射爱心...");
                    nettyMessage.setMessageType("1");
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(nettyMessage)));
                }
            }
        }
    }

}
